package zhao.ben.quan.service;

import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import zhao.ben.quan.pojo.Permission;
import zhao.ben.quan.pojo.Role;
import zhao.ben.quan.pojo.User;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component//给spring扫描
public class SpringSecurityUserService implements UserDetailsService {

    @Reference
    private UserService userService;


    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        //从数据库查询用户信息
        User user = userService.findByUsername(name);

        if(user==null){
            return null;
        }
        //创建list集合
        List<GrantedAuthority> list = new ArrayList<>();
        Set<Role> roles = user.getRoles();//获取用户的角色信息

        for (Role role : roles) {
            list.add(new SimpleGrantedAuthority(role.getKeyword()));//授予角色
            Set<Permission> permissions = role.getPermissions();//每个角色对应的权限
            for (Permission permission : permissions) {
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));//授权限
            }
        }
        org.springframework.security.core.userdetails.User userSecurity = new org.springframework.security.core.userdetails.User(name,user.getPassword(),list);

        return userSecurity;
    }
}
